package ChatRoom;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ClientSerice extends Frame {
 Socket s = null;
 DataOutputStream dos = null;
 DataInputStream dis = null;
 private boolean cont = false;
 
 TextField tfTxt = new TextField();
 TextArea taContent = new TextArea();
 
 Thread tRecv = new Thread(new RecvThread());
 
 public static void main(String[] args) {
  new ClientSerice().launchFrame();
 }
 
 public void launchFrame() {
  setLocation(400, 300);
  this.setSize(300, 300);
  add(tfTxt,BorderLayout.SOUTH);
  add(taContent,BorderLayout.NORTH);
  pack(); //包在一起，去掉中间空着的
  this.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
    disconnect();
    System.exit(0);
   }
  });
  tfTxt.addActionListener(new TfListent());
  setVisible(true);
  connect();
  tRecv.start();   //启动线程
 }
 
 public void connect(){
  try {
   s = new Socket("127.0.0.1",8888);//注意不要定义成Socket s,这就成了局部变量而不是成员变量了
System.out.println("connected!");
   dos = new DataOutputStream(s.getOutputStream());
   dis = new DataInputStream(s.getInputStream());
   cont = true;
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
 }
 
 public void disconnect(){
  try {
   dos.close(); 
   dis.close();
   s.close();
  } catch (IOException e) {
   e.printStackTrace();
  } 
  
  /*//无法解决readUTF阻塞式方法
  try {
   cont = false;  //关闭线程 
   tRecv.join();  //合并线程，彻底让他停止
  } catch (InterruptedException  e) {
   e.printStackTrace();
  } finally {
   try {
    dos.close(); //线程停止之后才能关流，不然抛SocketException异常
    dis.close();
    s.close();
   } catch (IOException e) {
    e.printStackTrace();
   } 
  }
  */
 }
 
 private class TfListent implements ActionListener {

  public void actionPerformed(ActionEvent e) {
   String str = tfTxt.getText().trim();
   tfTxt.setText("");
   
   try {
    dos.writeUTF(str);
    dos.flush();
 
   } catch (IOException e1) {
    e1.printStackTrace();
   }
   
  }
  
 }

 private class RecvThread implements Runnable{
  
  public void run() {
   try {
    while(cont){
     String str = dis.readUTF();
     taContent.setText(taContent.getText() + str + '\n');
    }
   } catch (SocketException e){
    System.out.println("退出了，bye!");
   } catch (IOException e) {   
    e.printStackTrace();
   }
  }
  
 }
}

